package org.zoomdev.zoom.protobuf.modules;

import io.protostuff.ByteArrayInput;
import io.protostuff.ProtostuffOutput;
import org.zoomdev.zoom.common.exceptions.ZoomException;
import org.zoomdev.zoom.common.utils.Creators;

import java.io.IOException;
import java.util.Collection;

public final class UnknownCollectionSchema implements ISchema {

    private final Class type;

    public UnknownCollectionSchema(Class type) {
        this.type = type;
    }

    @Override
    public void write(ProtostuffOutput output, int index, Object value, boolean repeat) throws IOException {
        Collection collection = (Collection) value;
        for (Object data : collection) {
            if (data == null) {
                throw new ZoomException("element is null");
            }
            ISchema schema = IUnknownSchemaRegistry.getSchema(data.getClass());
            schema.write(output, index, data, false);
        }
    }

    @Override
    public Object mergeFrom(ByteArrayInput input) throws IOException {
        Collection list = Creators.newCollection(type);

        while (true) {
            int number = input.readFieldNumber(null);
            if (number == 0) {
                break;
            }
            int index = input.readInt32();
            number = input.readFieldNumber(null);
            if (number == 0) {
                break;
            }
            ISchema schema = IUnknownSchemaRegistry.getSchema(index);
            list.add(schema.mergeFrom(input));
        }


        return list;
    }
}
